import tkinter
import time
import random
class Ball():
    def __init__(self,canvas,paddle,score,color):
        self.canvas=canvas
        self.paddle=paddle
        self.score=score
        self.id=canvas.create_oval(0,0,30,30,fill=color)
        canvas.move(self.id,245,100)
        level=[-7,-5,-3,-1,1,3,5,7]
        self.x=random.choice(level)
        self.y=random.choice(level)
        self.hit_bottom=False
    def draw(self):
        self.canvas.move(self.id,self.x,self.y)
        pos=self.canvas.coords(self.id)
        if self.hit_paddle(pos) == True:
            self.y=-3
        if pos[3]>=400:
            self.hit_bottom=True
        if pos[1]<=0:
            self.y=3
        if pos[0]<=0:
            self.x=3
        if pos[2]>=500:
            self.x=-3
    def hit_paddle(self,pos):
        paddle_pos=self.canvas.coords(self.paddle.id)
        if pos [2]>=paddle_pos[0]and pos[0]<=paddle_pos[2]:
            if pos[3]>=paddle_pos[1]and pos[3]<=paddle_pos[3]:
                self.x=self.x+self.paddle.x
                self.score.hit()
                return True
            return False
class  Paddle():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0, 0, 300, 20, fill=color)
        canvas.move(self.id, 100, 300)
        self.x=0
        self.y=0
        self.canvas.bind_all('<KeyPress-Left>',self.turn_left)
        self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
        self.canvas.bind_all('<Button-1>',self.start_game)
        self.start=False
    def start_game(self,evt):
        self.start= True
    def draw(self):
        self.canvas.move(self.id,self.x,self.y)
        pos=self.canvas.coords(self.id)
        if pos[3]>=400:
            self.y=-3
        if pos[1]<=0:
            self.y=3
        if pos[0]<=0:
            self.x=3
        if pos[2]>=500:
            self.x=-3
    def turn_left(self,evt):
        self.x=-3
    def turn_right(self, evt):
        self.x=3
class Score():
    def __init__(self,canvas,color):
        self.canvas=canvas
        self.score=0
        self.id=canvas.create_text(450,20,text=self.score,font=("Arial",30),fill=color)
    def hit(self):
        self.score=self.score+1
        canvas.itemconfig(self.id,text=self.score)
tk=tkinter.Tk()
tk.title("第一个自己做的小游戏")
tk.resizable(0,0)
tk.wm_attributes('-topmost',1)
canvas=tkinter.Canvas(tk,width=500,height=400)
canvas.pack()
tk.update()
score=Score(canvas,"red")
paddle=Paddle(canvas,"blue")
ball=Ball(canvas,paddle,score,"red")
game_over_text=canvas.create_text(250,250,text="hehe，游戏结束",font=("Arail",30),state='hidden')
while 1:
    if ball.hit_bottom==False and paddle.start==True:
        ball.draw()
        paddle.draw()
    if ball.hit_bottom==True:
        canvas.itemconfig(game_over_text,start='normal')
    tk.update_idletasks()
    tk.update()
    time.sleep(0.01)